package com.qeeyou.apps.android.craftsman.activity.publish;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.TimePickerView;
import com.qeeyou.apps.android.craftsman.R;
import com.qeeyou.apps.android.craftsman.common.Contants;
import com.qeeyou.apps.android.craftsman.po.AreaInfo;
import com.qeeyou.apps.android.craftsman.po.InstallMaterialInfo;
import com.qeeyou.apps.android.craftsman.po.InstallMaterialPriceInfo;
import com.qeeyou.apps.android.craftsman.po.InstallMethodInfo;
import com.qeeyou.apps.android.craftsman.po.InstallShopInfo;
import com.qeeyou.apps.android.craftsman.po.InstallTypeInfo;
import com.qeeyou.apps.android.craftsman.po.UserAddressInfo;
import com.qeeyou.apps.android.craftsman.po_wrap.InstallMaterialWrapInfo;
import com.qeeyou.apps.android.craftsman.service.AppService;
import com.qeeyou.apps.android.craftsman.service.UserService;
import com.qeeyou.apps.android.craftsman.view.CustomLoadingDialog;
import com.qeeyou.apps.android.craftsman.view.PublishSelectButton;
import com.qeeyou.apps.android.craftsman.view.PublishSelectButton2;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Publish3Activity extends Activity {

    private ImageView btnBack;
    private LinearLayout btnAddress;
    private LinearLayout btnNext;

    private PublishSelectButton btnInstallTime;               //安装时间
    private PublishSelectButton2 btnInstallType;              //安装类型
    private PublishSelectButton2 btnInstallMaterial;          //安装材质
    private EditText editInstallPrice;                        //安装价格
    private TextView txtvPrice;

    private TextView tvAddressName;                           //地址用户名
    private TextView tvAddressPhone;                          //地址手机号
    private TextView tvAddress;                               //地址

    private CustomLoadingDialog mLoadingDialog;
    private List<AreaInfo> mAreaList = new ArrayList<AreaInfo>();

    private List<InstallTypeInfo> mInstallTypeList = new ArrayList<>();
    private InstallShopInfo mInstallShopInfo;
    private UserAddressInfo mUserAddressInfo;
    private InstallTypeInfo mInstallTypeInfo;
    private InstallMaterialWrapInfo mInstallMaterialInfo;
    private InstallMethodInfo mInstallMethodInfo;
    private String mInstallTime;
    private String mInstallPrice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish3);

        Intent intent = getIntent();
        if(intent != null && intent.getSerializableExtra("shopInfo") != null) {
            mInstallShopInfo = (InstallShopInfo) intent.getSerializableExtra("shopInfo");
        }

        setView();
        setEvent();

        loadData();

    }

    private void setView() {
        btnBack = (ImageView) this.findViewById(R.id.btnBack4Publish3);
        btnAddress = (LinearLayout) this.findViewById(R.id.btnAddress4Publish3);
        btnNext = (LinearLayout) this.findViewById(R.id.btnNext4Publish3);

        btnInstallTime = (PublishSelectButton) this.findViewById(R.id.btnInstallTime4Publish3);
        btnInstallType = (PublishSelectButton2) this.findViewById(R.id.btnInstallType4Publish3);
        btnInstallMaterial = (PublishSelectButton2) this.findViewById(R.id.btnInstallMaterial4Publish3);
        editInstallPrice = (EditText) this.findViewById(R.id.editInstallPrice4Publish3);
        txtvPrice = (TextView) this.findViewById(R.id.txtvPrice4Publish3);

        tvAddressName = (TextView) this.findViewById(R.id.tvAddressName4Publish3);
        tvAddressPhone = (TextView) this.findViewById(R.id.tvAddressPhone4Publish3);
        tvAddress = (TextView) this.findViewById(R.id.tvAddress4Publish3);
    }

    private void setEvent() {
        btnBack.setOnClickListener(onBackClickListener);
        btnAddress.setOnClickListener(onAddressClickListener);
        btnNext.setOnClickListener(onNextClickListener);
        btnInstallTime.setOnClickListener(onInstallTimeClickListener);
        btnInstallType.setOnClickListener(onInstallTypeClickListener);
        btnInstallMaterial.setOnClickListener(onInstallMaterialClickListener);
        editInstallPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mInstallPrice = editInstallPrice.getText().toString();
                txtvPrice.setText("￥" + mInstallPrice + "元");
            }
        });
    }

    private void loadData() {
        new Publish3Activity.GetUserAddressList().execute();
        String[] params = {"2"};
        new Publish3Activity.GetInstallTypeList().execute(params);
    }

    //返回按钮
    private View.OnClickListener onBackClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Publish3Activity.this.finish();
        }
    };

    //地址按钮
    private View.OnClickListener onAddressClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Publish3Activity.this, AddressActivity.class);
            Publish3Activity.this.startActivityForResult(intent, Contants.RequestCode.REQUEST_SELECT_ADDRESS);
        }
    };

    //上门安装时间
    private View.OnClickListener onInstallTimeClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            TimePickerView pickerView = new TimePickerView.Builder(Publish3Activity.this, new TimePickerView.OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    String dateStr = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(date);
                    btnInstallTime.setText(dateStr);
                    mInstallTime = dateStr;
                }
            }).setType(new boolean[]{true, true, true, true, true, false})
                    .setRange(Calendar.getInstance().get(Calendar.YEAR) - 5, Calendar.getInstance().get(Calendar.YEAR) + 5).build();
            pickerView.setDate(Calendar.getInstance());
            pickerView.show();
        }
    };

    //安装类型
    private View.OnClickListener onInstallTypeClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Publish3Activity.this, InstallTypeActivity.class);
            Publish3Activity.this.startActivityForResult(intent, Contants.RequestCode.REQUEST_CODE_INSTALL_TYPE);
        }
    };

    //安装材质
    private View.OnClickListener onInstallMaterialClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Publish3Activity.this, InstallMaterialActivity.class);
            Publish3Activity.this.startActivityForResult(intent, Contants.RequestCode.REQUEST_CODE_INSTALL_MATERIAL);
        }
    };


    //下一步按钮
    private View.OnClickListener onNextClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(mInstallShopInfo == null) {
                Toast.makeText(Publish3Activity.this, "订单有误", Toast.LENGTH_SHORT).show();
                return;
            }
            if(mUserAddressInfo == null) {
                Toast.makeText(Publish3Activity.this, "请添加用户地址", Toast.LENGTH_SHORT).show();
                return;
            }
            if(mInstallTime == null || mInstallTime.trim().equalsIgnoreCase("")) {
                Toast.makeText(Publish3Activity.this, "请输入安装时间", Toast.LENGTH_SHORT).show();
                return;
            }
            if(mInstallTypeInfo == null) {
                Toast.makeText(Publish3Activity.this, "请选择安装类型", Toast.LENGTH_SHORT).show();
                return;
            }
            if(mInstallMaterialInfo == null) {
                Toast.makeText(Publish3Activity.this, "请选择安装材质", Toast.LENGTH_SHORT).show();
                return;
            }
            mInstallPrice = editInstallPrice.getText().toString();
            if(mInstallPrice == null || mInstallPrice.trim().equalsIgnoreCase("")) {
                Toast.makeText(Publish3Activity.this, "请输入安装价格", Toast.LENGTH_SHORT).show();
                return;
            }

            Intent intent = new Intent(Publish3Activity.this, PublishStep2Activity.class);
            intent.putExtra(Contants.Extra.EXTRA_INSTALL_SHOP, mInstallShopInfo);
            intent.putExtra(Contants.Extra.EXTRA_ADDRESS_INFO, mUserAddressInfo);
            intent.putExtra(Contants.Extra.EXTRA_INSTALL_TYPE, mInstallTypeInfo);
            intent.putExtra(Contants.Extra.EXTRA_INSTALL_MATERIAL, mInstallMaterialInfo);
            intent.putExtra(Contants.Extra.EXTRA_INSTALL_TIME, mInstallTime);
            intent.putExtra(Contants.Extra.EXTRA_INSTALL_PRICE, mInstallPrice);
            Publish3Activity.this.startActivity(intent);
        }
    };

    class GetUserAddressList extends AsyncTask<String, Void, List<UserAddressInfo>> {

        public GetUserAddressList() {
            super();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (mLoadingDialog == null) {
                mLoadingDialog = new CustomLoadingDialog(Publish3Activity.this);
            }
            mLoadingDialog.setMessage("正在获取用户地址列表...");
            mLoadingDialog.show();
        }

        @Override
        protected List<UserAddressInfo> doInBackground(String... params) {
            Map<String, String> paramMap = new HashMap<String, String>();
            List<UserAddressInfo> masterList = UserService.getInstance().getUserAddressList(paramMap);
            return masterList;
        }

        @Override
        protected void onPostExecute(List<UserAddressInfo> addressList) {
            super.onPostExecute(addressList);
            if (mLoadingDialog != null) {
                mLoadingDialog.dismiss();
                mLoadingDialog = null;
            }
            if (addressList != null && addressList.size() > 0) {
                for (UserAddressInfo addressInfo : addressList) {
                    if (addressInfo.getIsdefault().equals("1")) {
                        mUserAddressInfo = addressInfo;
                        break;
                    }
                }
            }

            if (mUserAddressInfo != null) {
                refreshAddressInfo(mUserAddressInfo);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case Contants.RequestCode.REQUEST_SELECT_ADDRESS:
                if (resultCode == RESULT_OK) {
                    mUserAddressInfo = data.getParcelableExtra(Contants.Extra.EXTRA_ADDRESS_INFO);
                    refreshAddressInfo(mUserAddressInfo);
                }
                break;
            case Contants.RequestCode.REQUEST_CODE_INSTALL_MATERIAL:
                if(resultCode == RESULT_OK) {
                    Intent intent = data;
                    InstallMaterialWrapInfo materialWrapInfo = (InstallMaterialWrapInfo) intent.getSerializableExtra("install_material");
                    InstallMaterialInfo materialInfo = materialWrapInfo.getMaterialInfo();
                    btnInstallMaterial.setText(materialInfo.getMaterialname());
                    mInstallMaterialInfo = materialWrapInfo;
                }
                break;
            case Contants.RequestCode.REQUEST_CODE_INSTALL_TYPE:
                if(resultCode == RESULT_OK) {
                    Intent intent = data;
                    InstallTypeInfo typeInfo = (InstallTypeInfo) intent.getSerializableExtra("install_type");
                    btnInstallType.setText(typeInfo.getTypename());
                    mInstallTypeInfo = typeInfo;
                }
                break;
            default:
                break;
        }
    }

    private void refreshAddressInfo(UserAddressInfo addressInfo) {
        tvAddressName.setText(addressInfo.getName());
        tvAddressPhone.setText(addressInfo.getContactway());
        String province = "";
        String city = "";
        if (!TextUtils.isEmpty(addressInfo.getProvinceid())
                && !TextUtils.isEmpty(addressInfo.getCityid())) {
            for (AreaInfo provinceInfo : mAreaList) {
                if (provinceInfo.getId().equals(addressInfo.getProvinceid())) {
                    province = provinceInfo.getName();
                    for (AreaInfo cityInfo : provinceInfo.getNexts()) {
                        if (cityInfo.getId().equals(addressInfo.getCityid())) {
                            city = cityInfo.getName();
                        }
                    }
                }
            }
        }
        tvAddress.setText(province + city + addressInfo.getAddress());
    }

    //获取安装类型
    class GetInstallTypeList extends AsyncTask<String, Void, List<InstallTypeInfo>> {
        public GetInstallTypeList() {
            super();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (mLoadingDialog == null) {
                mLoadingDialog = new CustomLoadingDialog(Publish3Activity.this);
            }
            mLoadingDialog.setMessage("正在获取安装类型...");
            mLoadingDialog.show();
        }

        @Override
        protected void onPostExecute(List<InstallTypeInfo> typeList) {
            super.onPostExecute(typeList);
            if (mLoadingDialog != null) {
                mLoadingDialog.dismiss();
                mLoadingDialog = null;
            }
            mInstallTypeList.clear();
            mInstallTypeList.addAll(typeList);
            //TODO -- 显示安装类型

        }

        @Override
        protected List<InstallTypeInfo> doInBackground(String... params) {
            String releaseType = params[0];
            Map<String, String> paramMap = new HashMap<String, String>();
            paramMap.put("releasetype", releaseType);
            List<InstallTypeInfo> typeList = AppService.getInstance().getInstallTypeList(paramMap);
            return typeList;
        }
    }
}
